﻿//利用lock 解决多线程同时访问同一个文件资源冲突被占用的问题
using System.Runtime.Caching;
using System.Text;

DateTime start = DateTime.Now;
int count = 100000;
Task[] tasks = new Task[count];
for (int i = 0; i < count; i++)
{
    tasks[i] = Com.RunTask(i);
}
Task.WaitAll(tasks);
DateTime end = DateTime.Now;
Console.WriteLine((end - start).TotalSeconds);
Console.ReadLine();

public class Com
{
    static readonly object _lockObj = new object();
    public static Task RunTask(int i)
    {
        return Task.Run(() =>
        {
            string txt = $"这是第{i}次的文本";
            Console.WriteLine(txt);
            WriteTxt(txt);
        });
    }
    private static MemoryCache cache = new MemoryCache("");
   // private static List<string> txtlist = new List<string>();
    private static StringBuilder txtBuilder = new StringBuilder();
    private static int count = 0;
    public static void WriteTxt(string txt)
    {
        lock (_lockObj)
        {
            //txtlist.Add(txt);
            //if (txtlist.Count == 10000)
            txtBuilder.AppendLine(DateTime.Now.ToString());
            txtBuilder.AppendLine(txt);
            count++;
            if(count==10000)
            {
                using (StreamWriter sw = new StreamWriter("test.txt", true))
                {
                    //txtlist.ForEach(txt =>
                    //{
                    //    sw.WriteLine(DateTime.Now);
                    //    sw.WriteLine(txt);
                    //});
                    sw.WriteLine(txtBuilder.ToString());
                    sw.Close();
                }
                // txtlist.Clear();
                txtBuilder.Clear();
                count = 0;
            }
        }
    }
}

